let jwt = require('jsonwebtoken');

module.exports = function () {
  return async (ctx, next) => {

    // 验证token是否有效
    // 开始验证
    let token = ctx['headers']['token'];
    if (token) {
      try {
        // 加签的时候 name pwd uid
        let res = jwt.verify(token, ctx.key);
        ctx.uid = res.uid;
        ctx.status = 200;
        return await next();
      } catch (e) {
        ctx.status = 401;
        return ctx.body = {
          code: -1,
          msg: '权限不足'
        };
      }
    } else {
      ctx.status = 401;
      return ctx.body = {
        code: -1,
        msg: '权限不足'
      };
    }
  };
};
